<?php
namespace app\api\model;

use think\Model;
use think\exception\ValidateException;

class OrderShansong extends Model
{
    protected $name = 'order_shansong';

    protected $autoWriteTimestamp = true;

    // 闪送订单状态
    const STATUS_ORDER_DISPATCH = 20;//派单中（转单改派中）
    const STATUS_ORDER_PICKUPING = 30;//待取货(已就位）
    const STATUS_ORDER_DELIVERY = 40;//闪送中(申请取消中、物品送回中、取消单客服介入中）
    const STATUS_ORDER_COMPLETED = 50;//已完成（已退款）
    const STATUS_ORDER_CANCELLED = 60;//已取消

    public static function statusOrderList()
    {
        return [
            self::STATUS_ORDER_DISPATCH => '派单中',
            self::STATUS_ORDER_PICKUPING => '待取货',
            self::STATUS_ORDER_DELIVERY => '配送中',
            self::STATUS_ORDER_COMPLETED => '已完成',
            self::STATUS_ORDER_CANCELLED => '已取消',
        ];
    }


    /**
     * 订单新增
     */
    public function ssOrderCreate($param)
    {
        // 创建
        try {
            $data['appid'] = $param['appid'] ?? '';//appid
            $data['third_number'] = $param['third_number'] ?? '';//配送平台订单号
            $data['sys_number'] = $param['sys_number']??'';//骑手系统订单号(系统生成)
            $data['call_number'] = $param['call_number'] ?? '';//调用方订单号
            $data['app_type'] = $param['app_type'] ?? 0;//第三方平台类型 1:闪送, 2:达达,3:蜂鸟

            $data['appoint_type'] =  $param['appoint_type'] ?? 0;//0:立即单, 1:预约单
            $data['appointment_date'] =  $param['appointment_date'] ?? 0;//预约取件时间
            $data['store_id'] =  $param['store_id'] ?? 0;//配送店铺ID

            $data['total_distance'] = $param['total_distance'] ?? 0;
            $data['total_weight'] = $param['total_weight'] ?? 0;
            $data['total_amount'] = $param['total_amount'] ?? 0;
            $data['coupon_save_fee'] = $param['coupon_save_fee'] ?? 0;
            $data['dynamic_subsidy_amount'] = $param['dynamic_subsidy_amount'] ?? 0;
            $data['total_fee_after_save'] = $param['total_fee_after_save'] ?? 0;
            $data['expect_receive_time'] = $param['expect_receive_time'] ?? '';
            $data['estimate_grab_second'] = $param['estimate_grab_second'] ?? 0;
            $data['estimate_receive_second'] = $param['estimate_receive_second'] ?? 0;
            $data['fee_info_list'] =  $param['fee_info_list'] ?? 0;
            $data['interest_dto_list'] =  $param['interest_dto_list'] ?? 0;
            $data['status'] = $param['status'] ?? 0;

            $data['good_type'] = $param['good_type'] ?? '';
            $data['weight'] = $param['weight'] ?? '';
            $data['remarks'] = $param['remarks'] ?? '';
            $data['addition_fee'] = $param['addition_fee'] ?? 0;
            $data['ordering_source_type'] = $param['ordering_source_type'] ?? 0;
            $data['ordering_source_no'] = $param['ordering_source_no'] ?? '';
            $data['goods_size_id'] = $param['goods_size_id'] ?? 0;
            $data['goods_price'] = $param['goods_price'] ?? 0;
            $data['quality_delivery'] = $param['quality_delivery'] ?? 0;
            $data['insurance'] = $param['insurance'] ?? 0;
            $data['insurance_pro_id'] = $param['insurance_pro_id'] ?? 0;
            $data['insurance_flag'] = $param['insurance_flag'] ?? 0;
            $data['expect_start_time'] = $param['expect_start_time'] ?? '';
            $data['expect_end_time'] = $param['expect_end_time'] ?? '';

            $result = $this->save($data);
            if ($result) {
                return result_success('success',$result);
            } else {
                return result_error('保存失败');
            }
        } catch (\Exception $e) {
            return result_error($e->getMessage());
        }
    }


    /**
     * 订单更新
     */
    public function ssOrderUpdate($param)
    {
        try {
            if (empty($param['third_number'])&&empty($param['sys_number'])&&empty($param['call_number'])&&empty($param['id'])){
                return  result_error('缺少必要更新条件');
            }

            $orderParam['total_distance'] = $param['total_distance'] ?? 0;
            $orderParam['total_weight'] = $param['total_weight'] ?? 0;
            $orderParam['total_amount'] = $param['total_amount'] ?? 0;
            if (isset($param['coupon_save_fee'])) $orderParam['coupon_save_fee'] = $param['coupon_save_fee'];
            $orderParam['dynamic_subsidy_amount'] = $param['dynamic_subsidy_amount'] ?? 0;
            if (isset($param['total_fee_after_save'])) $orderParam['total_fee_after_save'] = $param['total_fee_after_save'];
            $orderParam['expect_receive_time'] = $param['expect_receive_time'] ?? 0;
            $orderParam['estimate_grab_second'] = $param['estimate_grab_second'] ?? 0;
            $orderParam['estimate_receive_second'] = $param['estimate_receive_second'] ?? 0;
            $orderParam['fee_info_list'] = !empty($param['fee_info_list']) ? json_encode($param['fee_info_list']) : '';
            $orderParam['interest_dto_list'] = !empty($param['interest_dto_list']) ? json_encode($param['interest_dto_list']) : '';
            $orderParam['status'] = $param['status'] ?? 0;
            $orderParam['status_desc'] = $param['status_desc'] ?? '';
            $orderParam['sub_status'] = $param['sub_status'] ?? 0;
            $orderParam['status_change_log'] = $param['status_change_log'] ?? '';
            $orderParam['sub_status_desc'] = !empty($param['sub_status_desc']) ? json_encode($param['sub_status_desc']) : '';
            if (isset($param['drawback']))$orderParam['drawback'] = $param['drawback'];
            if (isset($param['send_back_fee']))$orderParam['send_back_fee'] = $param['send_back_fee'];
            $orderParam['delivery_pwd'] = $param['delivery_password'] ?? '';
            $orderParam['pickup_pwd'] = $param['pickup_password'] ?? '';
            if (isset($param['deduct_amount']))$orderParam['deduct_amount'] = $param['deduct_amount'];
            $orderParam['abort_type'] = $param['abort_type'] ?? 0;
            $orderParam['punish_type'] = $param['punish_type'] ?? 0;
            $orderParam['abort_reason'] = $param['abort_reason'] ?? '';
            $orderParam['courier_id'] = $param['courier_id'] ?? 0;
            $orderParam = array_filter($orderParam);

            $find = $this
                ->when(!empty($param['third_number']),function ($query) use($param) {
                    $query->where('third_number', $param['third_number']);
                })
                ->when(!empty($param['sys_number']),function ($query) use($param) {
                    $query->where('sys_number', $param['sys_number']);
                })
                ->when(!empty($param['call_number']),function ($query) use($param) {
                    $query->where('call_number', $param['call_number']);
                })
                ->when(!empty($param['id']),function ($query) use($param) {
                    $query->where('id', $param['id']);
                })
                ->find();
            if (!$find){
                return  result_error('未查询到闪送订单');
            }

            $result=$find->save($orderParam);

            if ($result) {
               return result_success('success',$result);
            } else {
               return result_error('保存失败');
            }
        } catch (\Exception $e) {
             return result_error($e->getMessage());
        }
    }


    /**
     * 订单加价
     */
    public function ssAdditionSave($param)
    {
        if (empty($param['third_number'])&&empty($param['sys_number'])&&empty($param['call_number'])&&empty($param['id'])){
                return  result_error('缺少必要更新条件');
        }

        try {
            validate([
                'addition_amount'  => 'require', //加价的金额（分）
            ])->message([
                'addition_amount.require'  => 'addition_amount必须传递',    
            ])->check($param);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }

        // 创建
        try {
              $find = $this
                    ->when(isset($param['third_number']),function ($query) use($param) {
                        $query->where('third_number', $param['third_number']);
                    })
                    ->when(isset($param['sys_number']),function ($query) use($param) {
                        $query->where('sys_number', $param['sys_number']);
                    })
                    ->when(isset($param['call_number']),function ($query) use($param) {
                        $query->where('call_number', $param['call_number']);
                    })
                    ->when(isset($param['id']),function ($query) use($param) {
                        $query->where('id', $param['id']);
                    })
                    ->find();
            if (!$find){
                 return  result_error('未查询到订单');
            }  

            $result=$find
                    ->setInc('total_amount', $param['addition_amount'])
                    ->setInc('total_fee_after_save', $param['addition_amount'])
                    ->setInc('addition_amount', $param['addition_amount']);

            if ($result) {
                return result_success('success',$result);
            } else {
                return result_error('保存失败');
            }
        } catch (\Exception $e) {
             return result_error($e->getMessage());
        }
    }
}